package cn.redragon.soa.config.web;

import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.SpecVersion;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;

@Configuration
@ConditionalOnWebApplication
@SecurityScheme(name = HttpHeaders.AUTHORIZATION, scheme = "bearer", type = SecuritySchemeType.HTTP, in = SecuritySchemeIn.HEADER)
public class OpenAPIConfig {

    @Bean
    public OpenAPI openAPI(@Value("${spring.application.name}") String appName) {
        return new OpenAPI(SpecVersion.V30)
            .info(this.apiInfo(appName))
            .security(this.securityRequirements());
    }

    private Info apiInfo(String appName) {
        String title = appName.toUpperCase().concat(" Api Documentation");
        return new Info().title(title).description(title).version("v1.0");
    }

    private List<SecurityRequirement> securityRequirements() {
        return List.of(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION));
    }
}